package com.itheima.controller;

import com.itheima.common.Result;
import com.itheima.pojo.Dept;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门管理Controller
 */
@Slf4j
@RequestMapping("/depts")
@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpService empService;

    /**
     * 查询部门列表
     *
     * @return
     */
    @GetMapping
    public Result<List<Dept>> list() {
        List<Dept> deptList = deptService.list();
        return Result.success(deptList);
    }

    /**
     * 根据ID删除部门
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> removeById(@PathVariable Integer id) throws Exception {
        long start = System.currentTimeMillis();
        deptService.removeById(id);
        // 删除部门下的员工 - 运行时异常
        empService.removeByDeptId(id);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        return Result.success();
    }

    /**
     * 新增部门
     *
     * @param dept dept
     * @return {@link Result}<{@link ?}>
     */
    @PostMapping
    public Result<?> create(@RequestBody Dept dept) {
        deptService.create(dept);
        return Result.success();
    }

}
